const { pool } = require('../config/db');
const { success, error } = require('../utils/response');
const moment = require('moment');
const { notifyNextReservation } = require('./reservationController');

/**
 * 管理员端借阅管理控制器
 */

// 获取所有借阅记录（管理员）
exports.getAllBorrowRecords = async (req, res, next) => {
  try {
    const { page = 1, limit = 10, status, keyword, user_type } = req.query;
    const offset = (page - 1) * limit;

    let whereClause = 'WHERE 1=1';
    let params = [];

    if (status) {
      whereClause += ' AND br.status = ?';
      params.push(status);
    }

    if (user_type) {
      whereClause += ' AND u.user_type = ?';
      params.push(user_type);
    }

    if (keyword) {
      whereClause += ' AND (u.username LIKE ? OR u.phone LIKE ? OR b.name LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`, `%${keyword}%`);
    }

    const [records] = await pool.query(`
      SELECT
        br.id,
        br.borrow_date,
        br.due_date,
        br.return_date,
        br.status,
        br.borrow_days,
        br.renew_count,
        u.id as user_id,
        u.username,
        u.phone,
        u.user_type,
        b.id as book_id,
        b.name as book_name,
        b.author,
        b.cover
      FROM borrow_records br
      LEFT JOIN users u ON br.user_id = u.id
      LEFT JOIN books b ON br.book_id = b.id
      ${whereClause}
      ORDER BY br.borrow_date DESC
      LIMIT ? OFFSET ?
    `, [...params, parseInt(limit), offset]);

    const [total] = await pool.query(`
      SELECT COUNT(*) as count
      FROM borrow_records br
      LEFT JOIN users u ON br.user_id = u.id
      LEFT JOIN books b ON br.book_id = b.id
      ${whereClause}
    `, params);

    success(res, {
      records,
      pagination: {
        current: parseInt(page),
        limit: parseInt(limit),
        total: total[0].count,
        pages: Math.ceil(total[0].count / limit)
      }
    });
  } catch (err) {
    next(err);
  }
};

// 管理员办理借阅（现场借阅）
exports.adminBorrowBook = async (req, res, next) => {
  const connection = await pool.getConnection();
  
  try {
    const { userId, bookId, borrowDays } = req.body;
    const adminId = req.userId;

    await connection.beginTransaction();

    // 检查图书库存
    const [books] = await connection.query(
      'SELECT id, name, stock FROM books WHERE id = ? AND stock > 0',
      [bookId]
    );

    if (books.length === 0) {
      await connection.rollback();
      return error(res, '图书不存在或库存不足', 400);
    }

    const book = books[0];

    // 检查用户是否已借阅此书
    const [existingBorrow] = await connection.query(
      'SELECT id FROM borrow_records WHERE user_id = ? AND book_id = ? AND status = "borrowed"',
      [userId, bookId]
    );

    if (existingBorrow.length > 0) {
      await connection.rollback();
      return error(res, '该用户已借阅此书', 400);
    }

    // 计算到期日期
    const defaultDays = parseInt(process.env.MAX_BORROW_DAYS) || 30;
    const actualDays = borrowDays || defaultDays;
    const dueDate = moment().add(actualDays, 'days').format('YYYY-MM-DD HH:mm:ss');

    // 创建借阅记录
    const [result] = await connection.query(
      'INSERT INTO borrow_records (user_id, book_id, borrow_date, due_date, borrow_days, approved_by, approve_time) VALUES (?, ?, NOW(), ?, ?, ?, NOW())',
      [userId, bookId, dueDate, actualDays, adminId]
    );

    // 减少库存
    await connection.query(
      'UPDATE books SET stock = stock - 1 WHERE id = ?',
      [bookId]
    );

    await connection.commit();

    success(res, {
      borrowId: result.insertId,
      bookName: book.name,
      dueDate: dueDate
    }, '借阅办理成功');

  } catch (err) {
    await connection.rollback();
    next(err);
  } finally {
    connection.release();
  }
};

// 管理员办理归还
exports.adminReturnBook = async (req, res, next) => {
  const connection = await pool.getConnection();
  
  try {
    const { borrowId, condition = 'good', notes } = req.body;
    const adminId = req.userId;

    await connection.beginTransaction();

    // 获取借阅记录
    const [records] = await connection.query(
      'SELECT br.*, b.name as book_name FROM borrow_records br LEFT JOIN books b ON br.book_id = b.id WHERE br.id = ? AND br.status = "borrowed"',
      [borrowId]
    );

    if (records.length === 0) {
      await connection.rollback();
      return error(res, '借阅记录不存在或已归还', 404);
    }

    const record = records[0];

    // 计算逾期和罚款
    const now = moment();
    const dueDate = moment(record.due_date);
    const isOverdue = now.isAfter(dueDate);
    const overdueDays = isOverdue ? now.diff(dueDate, 'days') : 0;
    const finePerDay = parseFloat(process.env.FINE_PER_DAY) || 1.00;
    const fineAmount = overdueDays * finePerDay;

    // 更新借阅记录
    await connection.query(
      'UPDATE borrow_records SET status = "returned", return_date = NOW(), condition_on_return = ?, fine_amount = ?, return_notes = ? WHERE id = ?',
      [condition, fineAmount, notes, borrowId]
    );

    // 增加库存
    await connection.query(
      'UPDATE books SET stock = stock + 1 WHERE id = ?',
      [record.book_id]
    );

    // 如果有逾期，创建逾期记录
    if (isOverdue && fineAmount > 0) {
      await connection.query(
        'INSERT INTO overdue_records (borrow_record_id, user_id, book_id, overdue_days, fine_amount) VALUES (?, ?, ?, ?, ?)',
        [borrowId, record.user_id, record.book_id, overdueDays, fineAmount]
      );
    }

    await connection.commit();

    // 归还后通知预约用户
    setTimeout(() => {
      notifyNextReservation(record.book_id);
    }, 100);

    success(res, {
      fineAmount: fineAmount,
      overdueDays: overdueDays,
      condition: condition,
      returnDate: moment().format('YYYY-MM-DD HH:mm:ss')
    }, '归还办理成功');

  } catch (err) {
    await connection.rollback();
    next(err);
  } finally {
    connection.release();
  }
};

// 获取借阅统计（管理员）
exports.getAdminBorrowStats = async (req, res, next) => {
  try {
    const [stats] = await pool.query(`
      SELECT
        COUNT(CASE WHEN status = 'borrowed' THEN 1 END) as borrowed_count,
        COUNT(CASE WHEN status = 'returned' THEN 1 END) as returned_count,
        COUNT(CASE WHEN status = 'overdue' THEN 1 END) as overdue_count,
        COUNT(*) as total_count
      FROM borrow_records
    `);

    // 今日借阅数
    const [todayStats] = await pool.query(`
      SELECT COUNT(*) as today_borrow_count
      FROM borrow_records
      WHERE DATE(borrow_date) = CURDATE()
    `);

    // 今日归还数
    const [todayReturnStats] = await pool.query(`
      SELECT COUNT(*) as today_return_count
      FROM borrow_records
      WHERE DATE(return_date) = CURDATE()
    `);

    success(res, {
      ...stats[0],
      today_borrow_count: todayStats[0].today_borrow_count,
      today_return_count: todayReturnStats[0].today_return_count
    });
  } catch (err) {
    next(err);
  }
};

// 获取逾期记录列表（管理员）
exports.getAdminOverdueRecords = async (req, res, next) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    const [records] = await pool.query(`
      SELECT
        br.id,
        br.borrow_date,
        br.due_date,
        u.id as user_id,
        u.username,
        u.phone,
        u.user_type,
        b.id as book_id,
        b.name as book_name,
        b.author,
        DATEDIFF(NOW(), br.due_date) as overdue_days
      FROM borrow_records br
      LEFT JOIN users u ON br.user_id = u.id
      LEFT JOIN books b ON br.book_id = b.id
      WHERE br.status = 'borrowed' AND br.due_date < NOW()
      ORDER BY br.due_date ASC
      LIMIT ? OFFSET ?
    `, [parseInt(limit), offset]);

    const [total] = await pool.query(`
      SELECT COUNT(*) as count
      FROM borrow_records
      WHERE status = 'borrowed' AND due_date < NOW()
    `);

    success(res, {
      records,
      pagination: {
        current: parseInt(page),
        limit: parseInt(limit),
        total: total[0].count,
        pages: Math.ceil(total[0].count / limit)
      }
    });
  } catch (err) {
    next(err);
  }
};

// 快速借阅（通过手机号和ISBN）
exports.quickBorrow = async (req, res, next) => {
  try {
    const { phone, isbn, borrowDays } = req.body;

    // 通过手机号查找用户
    const [users] = await pool.query(
      'SELECT id, username, phone FROM users WHERE phone = ?',
      [phone]
    );

    if (users.length === 0) {
      return error(res, '用户不存在', 404);
    }

    const user = users[0];

    // 通过ISBN查找图书
    const [books] = await pool.query(
      'SELECT id, name, stock FROM books WHERE isbn = ? AND stock > 0',
      [isbn]
    );

    if (books.length === 0) {
      return error(res, '图书不存在或库存不足', 404);
    }

    const book = books[0];

    // 调用借阅功能
    req.body.userId = user.id;
    req.body.bookId = book.id;
    await exports.adminBorrowBook(req, res, next);

  } catch (err) {
    next(err);
  }
};

